package kode.boot.file.autoconfigure;

import kode.boot.file.api.FileMetadataService;
import kode.boot.file.api.FileService;
import kode.boot.file.local.LocalFileService;
import kode.boot.file.simple.SimpleFileMetadataRepo;
import kode.boot.file.simple.SimpleFileMetadataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import javax.sql.DataSource;

/**
 * FileServiceAutoConfiguration
 *
 * @author Stark
 * @date 2019/1/4
 */
@SuppressWarnings("rawtypes")
@Configuration
@ConditionalOnClass({FileService.class, FileMetadataService.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@EnableConfigurationProperties(FileServiceProperties.class)
public class FileServiceAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean(FileService.class)
	public FileService localFileService(FileServiceProperties fileServiceProperties) {
		LocalFileService fileService = new LocalFileService();
		fileService.setLocalFileProperties(fileServiceProperties.getLocal());
		return fileService;
	}

	@Configuration
	@ConditionalOnBean(DataSource.class)
	@ConditionalOnClass({JpaRepository.class, SimpleFileMetadataRepo.class})
	@ConditionalOnMissingBean(FileMetadataService.class)
	public static class FileMetadataServiceConfiguration {

		@Configuration
		@EntityScan("kode.boot.file.simple")
		@ComponentScan("kode.boot.file.simple")
		@EnableJpaRepositories({"kode.boot.file.simple"})
		static class JpaConfiguration {

			@Autowired
			public SimpleFileMetadataRepo simpleFileMetadataRepo;

			@Bean
			@ConditionalOnMissingBean(FileMetadataService.class)
			public FileMetadataService simpleFileMetadataService() {
				return new SimpleFileMetadataService();
			}
		}
	}
}
